<template>
    <div class="goodslist">
        <Header brack title='JD商城 ~列表内容'>
            <template #left>
                <van-icon name="arrow-left" @click="tobackFn" />
            </template>
        </Header>
        <!--  -->
        <van-card v-for="item in goodsList" :num="item.isseckill" :price="item.originprice" :desc="item.desc"
            :title="item.category" :thumb="item.img1">
            <template #footer>
                <van-button size="mini" color="#7232dd" @click="XiangQingFn(item.proid)">查看详情</van-button>
                <van-button size="mini" color="linear-gradient(to right, #ff6034, #ee0a24)"
                    @click="GouMai(item.proid)">加入购物车</van-button>
            </template>
        </van-card>

    </div>
</template>

<script setup lang="ts">
// import Header from '@/views/Header/header.vue'
//当来过这个页面就需要把内容存在localstorage中
import { useRoute, type RouteLocationNormalizedLoaded } from 'vue-router';
import { onMounted, ref } from 'vue';
import { Toast } from 'vant'
import { SearchListApi } from '@/api/goods'
import type { MyMiaoSaItem } from '@/config/interface'
import { useRouter, type Router } from 'vue-router';
import { cartAddApi } from '@/api/cart'
import router from '@/router';
const $route: RouteLocationNormalizedLoaded = useRoute()
const $router: Router = useRouter()

//准备一个函数，接收带过来的参数存储在浏览器中
const setLocalStorage = (text: string) => {
    const historyList: string[] = JSON.parse(window.localStorage.getItem('history') as string) || []
    //如果历史记录数组中historyList中有这个数据那么不需要存进去，没有的话存进去
    const res = historyList.indexOf(text) !== -1
    if (res) return   //说明有这条记录，直接return

    //代码执行到这里，说明没有该信息，就把这条信息存储进去
    historyList.push(text)
    //再把最新的数组存储到浏览器内
    window.localStorage.setItem('history', JSON.stringify(historyList))
}

//根据关键字请求当前页面的数据
// 准备一个数据表示当前第几页
const count = ref<number>(1)
//准备一个渲染的数组
const goodsList = ref<MyMiaoSaItem[]>([])

const getGoodsList = async (text: string) => {
    const res = await SearchListApi(text, count.value)
    console.log(123, res);
    goodsList.value = res.data
}
// 详情页
const XiangQingFn = (id: string) => {
    console.log(`查看id为${id}的内容`);
    $router.push({ path: '/xiangqing', query: { proid: id } })
}

//加入购物车
const GouMai = async(id: string) => {
    console.log(`加入购物车 id为${id}的内容`);
    // 获取一次 用户id 和 token(为了验证有没有)
    const user_id = window.localStorage.getItem('user_id')
    const token = window.localStorage.getItem('token')
    
    // 做一次非空元整
    if (!user_id || !token) {
        // 您还没有登录, 请登录后再试
        Toast({
            message: '您还没有登录'
        })
        return
    }
    //代码到了这里说明有token 和user_id

    const res = await cartAddApi(user_id, id)
    console.log(111,res);
    
     // 判断
  if (res.code === '200') Toast({ message: '加入购物车成功' })

}

onMounted(() => {
    // console.log($route, 123);
    setLocalStorage('')
    const searchText = $route.query.search   //获取到的是用户点击记录后传过来的产品名称
    //防止用户直接点进商品列表页报错，只有用户点击记录进来之后才可以执行setLocalStorage（）
    searchText && setLocalStorage(searchText as string)
    searchText && getGoodsList(searchText as string)
})


//返回上一页
const tobackFn = () => {
    router.go(-1)
}



</script>
<style scoped lang="scss">

</style>